import { OPEN_AUDIO } from '../actionTypes';
import { hashHistory } from 'react-router';
import { parse2Minutes, parse2Seconds } from '../utils/libs';

export const update = (payload) => ({
  type: OPEN_AUDIO,
  payload,
});

export const plus = (id) => (dispatch, getState) => {
  const { playList } = getState().openAudio;
  const times = (playList[id] || 0) + 1;
  dispatch(update({
    playList: {
      ...playList,
      [id]: times,
    }
  }));
  dispatch(calcTotal());
};

export const minus = (id) => (dispatch, getState) => {
  const { playList } = getState().openAudio;
  const newPlayList = { ...playList };
  const times = (playList[id] || 0) - 1;
  if (times > 0) {
    dispatch(update({
      playList: {
        ...playList,
        [id]: times,
      }
    }));
  } else {
    delete newPlayList[id];
    dispatch(update({
      playList: {
        ...newPlayList,
      }
    }));
  }
  dispatch(calcTotal());
};

export const selectAll = () => (dispatch, getState) => {
  const { type } = getState().openAudio;
  const audioType = `audio${type}`;
  const audioList = getState().openAudio[audioType] || [];
  const playList = {};
  audioList.forEach(item => {
    playList[item.id] = 1;
  });
  dispatch(update({
    all: true,
    playList,
  }));
  dispatch(calcTotal());
};

export const removeAll = () => (dispatch) => {
  dispatch(update({
    all: false,
    playList: {},
    total: 0,
    duration: '00:00'
  }));
};

export const calcTotal = () => (dispatch, getState) => {
  const { type, playList } = getState().openAudio;
  const audioType = `audio${type}`;
  const audioList = getState().openAudio[audioType] || [];
  const list = Object.keys(playList).filter(item => playList[item] > 0) || [];
  const duration = list.reduce((acc, cur) => {
    const curTimes = playList[cur];
    const curDuration = audioList.filter(item => item.id === +cur)[0].duration;

    return acc + curTimes * parse2Seconds(curDuration);
  }, 0);


  dispatch(update({
    total: list.length,
    duration: parse2Minutes(duration),
  }));
};

export const goDetail = () => (dispatch, getState) => {
  const { playList } = getState().openAudio;
  const id = Object.keys(playList)[0];
  hashHistory.push(`/open/audio/detail?id=${id}`);
};
